import 'package:efood_multivendor/controller/cart_controller.dart';
import 'package:efood_multivendor/controller/category_controller.dart';
import 'package:efood_multivendor/controller/localization_controller.dart';
import 'package:efood_multivendor/data/model/response/product_model.dart';
import 'package:efood_multivendor/data/model/response/restaurant_model.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/dimensions.dart';

import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/cart_view.dart';
import 'package:efood_multivendor/view/base/product_view.dart';
import 'package:efood_multivendor/view/screens/restaurant/widget/category_list.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class CategoryProductScreen extends StatefulWidget {
  final String categoryID;
  final String categoryName;

  CategoryProductScreen({required this.categoryID, required this.categoryName});

  @override
  _CategoryProductScreenState createState() => _CategoryProductScreenState();
}

class _CategoryProductScreenState extends State<CategoryProductScreen>
    with TickerProviderStateMixin {
  final ScrollController scrollController = ScrollController();
  final ScrollController restaurantScrollController = ScrollController();
  final bool _ltr = Get.find<LocalizationController>().isLtr;

  late TabController _tabController;
  bool _exists = false;
  static const String AlcoholDrinks = "alcohol";
  static const String Supermarket = "supermarket";

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, initialIndex: 0, vsync: this);
    Get.find<CategoryController>().getSubCategoryList(widget.categoryID);
    restaurantScrollController.addListener(() {
      if (scrollController.position.pixels ==
              scrollController.position.maxScrollExtent &&
          Get.find<CategoryController>().categoryProductList != null &&
          !Get.find<CategoryController>().isLoading) {
        int pageSize = (Get.find<CategoryController>().pageSize! / 10).ceil();
        if (Get.find<CategoryController>().offset < pageSize) {
          Get.find<CategoryController>().showBottomLoader();
          Get.find<CategoryController>().getCategoryProductList(
            Get.find<CategoryController>().subCategoryIndex == 0
                ? widget.categoryID
                : Get.find<CategoryController>()
                    .subCategoryList![
                        Get.find<CategoryController>().subCategoryIndex]
                    .id
                    .toString(),
            Get.find<CategoryController>().offset + 1,
            Get.find<CategoryController>().type,
            false,
          );
        }
      }
    });
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
              scrollController.position.maxScrollExtent &&
          Get.find<CategoryController>().categoryRestList != null &&
          !Get.find<CategoryController>().isLoading) {
        int pageSize =
            (Get.find<CategoryController>().restPageSize! / 10).ceil();
        if (Get.find<CategoryController>().offset < pageSize) {
          Get.find<CategoryController>().showBottomLoader();
          Get.find<CategoryController>().getCategoryRestaurantList(
            Get.find<CategoryController>().subCategoryIndex == 0
                ? widget.categoryID
                : Get.find<CategoryController>()
                    .subCategoryList![
                        Get.find<CategoryController>().subCategoryIndex]
                    .id
                    .toString(),
            Get.find<CategoryController>().offset + 1,
            Get.find<CategoryController>().type,
            false,
          );
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CategoryController>(builder: (catController) {
      List<Product>? _products;
      List<Restaurant>? _restaurants;
      if (catController.categoryProductList != null) {
        _products = [];
        if (catController.isSearching) {
          _products.addAll(catController.searchProductList);
        } else {
          _products.addAll(catController.categoryProductList ?? []);
        }
      }
      if (catController.categoryRestList != null) {
        _restaurants = [];
        if (catController.isSearching) {
          _restaurants.addAll(catController.searchRestList);
        } else {
          _restaurants.addAll(catController.categoryRestList ?? []);
        }
      }

      return WillPopScope(onWillPop: () async {
        if (catController.isSearching) {
          catController.toggleSearch();
          return false;
        } else {
          return true;
        }
      }, child: GetBuilder<CartController>(builder: (cartController) {
        return Scaffold(
          appBar: AppBar(
            title: catController.isSearching
                ? TextField(
                    autofocus: true,
                    textInputAction: TextInputAction.search,
                    decoration: InputDecoration(
                      hintText: 'Search...',
                      border: InputBorder.none,
                    ),
                    style:
                        sfRegular.copyWith(fontSize: Dimensions.fontSizeLarge),
                    onSubmitted: (String query) => catController.searchData(
                      query,
                      catController.subCategoryIndex == 0
                          ? widget.categoryID
                          : catController
                              .subCategoryList![catController.subCategoryIndex]
                              .id
                              .toString(),
                      catController.type,
                    ),
                  )
                : Text(widget.categoryName.tr,
                    style: sfRegular.copyWith(
                      fontSize: Dimensions.fontSizeLarge,
                      color: Theme.of(context).textTheme.bodyMedium?.color,
                    )),
            centerTitle: true,
            leading: IconButton(
              icon: Icon(Icons.arrow_back_ios),
              color: Theme.of(context).textTheme.bodyMedium?.color,
              onPressed: () {
                catController.setRestaurant(true);

                if (catController.isSearching) {
                  catController.toggleSearch();
                } else {
                  Get.back();
                }
              },
            ),
            backgroundColor: Theme.of(context).cardColor,
            elevation: 0,
            actions: [
              IconButton(
                onPressed: () => catController.toggleSearch(),
                icon: Icon(
                  catController.isSearching ? Icons.close_sharp : Icons.search,
                  color: Theme.of(context).textTheme.bodyMedium?.color,
                ),
              ),
            ],
          ),
          body: CartView(
            Stack(
              children: [
                Center(
                    child: SizedBox(
                  width: Dimensions.WEB_MAX_WIDTH,
                  child: Column(children: [
                    (widget.categoryName
                                .toLowerCase()
                                .compareTo(AlcoholDrinks) ==
                            0)
                        ? Text(
                            'alcohol_msg'.tr,
                            style: sfRegular.copyWith(color: Colors.red),
                            textAlign: TextAlign.center,
                          )
                        : (widget.categoryName
                                    .toLowerCase()
                                    .compareTo(Supermarket) ==
                                0)
                            ? Text(
                                'supermarket_msg'.tr,
                                style: sfRegular,
                                maxLines: 2,
                                textAlign: TextAlign.center,
                              )
                            : SizedBox(),
                    Center(
                        child: Container(
                      width: Dimensions.WEB_MAX_WIDTH,
                      color: Theme.of(context).cardColor,
                      child: TabBar(
                        controller: _tabController,
                        indicatorColor: Theme.of(context).colorScheme.secondary,
                        indicatorWeight: 3,
                        indicator: UnderlineTabIndicator(
                          borderSide: BorderSide(
                              color: Theme.of(context).colorScheme.secondary,
                              width: 3.0),
                          insets: EdgeInsets.fromLTRB(50.0, 40.0, 50.0, 0.0),
                        ),
                        labelColor: Theme.of(context).colorScheme.secondary,
                        unselectedLabelColor: Theme.of(context).disabledColor,
                        unselectedLabelStyle: sfRegular.copyWith(
                            color: Theme.of(context).disabledColor,
                            fontSize: Dimensions.fontSizeSmall),
                        labelStyle: sfBold.copyWith(
                            fontSize: Dimensions.fontSizeSmall,
                            color: Theme.of(context).primaryColor),
                        tabs: [
                          Tab(
                              text: (widget.categoryName
                                          .toLowerCase()
                                          .compareTo(Supermarket) ==
                                      0)
                                  ? 'vendor'.tr
                                  : 'restaurants'.tr),
                          Tab(
                              text: (widget.categoryName
                                          .toLowerCase()
                                          .compareTo(Supermarket) ==
                                      0)
                                  ? 'supermarket_item'.tr
                                  : 'food'.tr),
                        ],
                      ),
                    )),
                    SizedBox(height: 1.h),
                    (catController.subCategoryList != null &&
                            !catController.isSearching)
                        ? Container(
                            height: 40,
                            width: Dimensions.WEB_MAX_WIDTH,
                            color: Theme.of(context).cardColor,
                            padding: EdgeInsets.symmetric(
                                vertical: Dimensions.PADDING_SIZE_EXTRA_SMALL),
                            child: ListView.builder(
                                scrollDirection: Axis.horizontal,
                                itemCount:
                                    catController.subCategoryList?.length ?? 0,
                                padding: EdgeInsets.only(
                                    left: Dimensions.PADDING_SIZE_SMALL),
                                physics: BouncingScrollPhysics(),
                                itemBuilder: (context, index) {
                                  return CategoryTabItem(
                                    index: index,
                                    catController: catController,
                                    categoryID: widget.categoryID,
                                    isSub: true,
                                  );
                                }),
                          )
                        : SizedBox(),
                    Expanded(
                        child: NotificationListener(
                      onNotification: (scrollNotification) {
                        if (scrollNotification is ScrollEndNotification) {
                          if ((_tabController.index == 0 &&
                                  !catController.isRestaurant) ||
                              _tabController.index == 1 &&
                                  catController.isRestaurant) {
                            catController
                                .setRestaurant(_tabController.index == 0);
                            if (catController.isSearching) {
                              catController.searchData(
                                catController.searchText,
                                catController.subCategoryIndex == 0
                                    ? widget.categoryID
                                    : catController
                                        .subCategoryList![
                                            catController.subCategoryIndex]
                                        .id
                                        .toString(),
                                catController.type,
                              );
                            } else {
                              if (_tabController.index == 1) {
                                catController.getCategoryProductList(
                                  catController.subCategoryIndex == 0
                                      ? widget.categoryID
                                      : catController
                                          .subCategoryList![
                                              catController.subCategoryIndex]
                                          .id
                                          .toString(),
                                  1,
                                  catController.type,
                                  false,
                                );
                              } else {
                                catController.getCategoryRestaurantList(
                                  catController.subCategoryIndex == 0
                                      ? widget.categoryID
                                      : catController
                                          .subCategoryList![
                                              catController.subCategoryIndex]
                                          .id
                                          .toString(),
                                  1,
                                  catController.type,
                                  false,
                                );
                              }
                            }
                          }
                        }
                        return false;
                      },
                      child: TabBarView(
                        controller: _tabController,
                        children: [
                          SingleChildScrollView(
                            controller: scrollController,
                            child: ProductView(
                              fromRestaurant: false,
                              fromCategory: true,
                              isRestaurant: true,
                              products: null,
                              restaurants: _restaurants ?? [],
                              noDataText: 'no_category_restaurant_found'.tr,
                            ),
                          ),
                          SingleChildScrollView(
                            controller: scrollController,
                            child: ProductView(
                              fromRestaurant: false,
                              fromCategory: true,
                              isRestaurant: false,
                              products: _products,
                              restaurants: [],
                              noDataText: 'no_category_food_found'.tr,
                            ),
                          ),
                        ],
                      ),
                    )),
                  ]),
                )),
                catController.isLoading
                    ? Positioned(
                        bottom: 10.h,
                        left: 45.w,
                        child: Center(
                            child: Padding(
                          padding:
                              EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
                          child: CircularProgressIndicator.adaptive(
                              valueColor: AlwaysStoppedAnimation<Color>(
                                  Theme.of(context).primaryColor)),
                        )),
                      )
                    : SizedBox(),
              ],
            ),
            "",
            restaurantId: cartController.currentCategory,
          ),
          extendBody: true,
          bottomNavigationBar: cartController.cartview,
        );
      }));
    });
  }
}
